import { chunk } from 'lodash';

// 拿到歌词, 解析歌词
export const getLyc = async (url) => {
  console.log(url)
  let res = await (await fetch(url)).text()
  let arr = res.split('\n')
  let lycArr = []
  for (const s of arr) {
    let arrStr = s.split(']');
    if (arrStr.length === 2) {
      let time = arrStr[0].replace('[', '')
      const [minute, second] = time.split(':')
      let obj = {
        time: parseInt(minute) * 60 + parseFloat(second),
        label: arrStr[1]
      }
      lycArr.push(obj)
    } else if (arrStr.length > 2) {
      let label = arrStr[arrStr.length - 1]
      for (let i = 0; i < arrStr.length - 1; i++) {
        let time = arrStr[i].replace('[', '')
        const [minute, second] = time.split(':')
        let obj = {
          time: parseInt(minute) * 60 + parseFloat(second),
          label
        }
        lycArr.push(obj)
      }
    }
  }
  lycArr.sort((first, second) => {
    return first.time - second.time
  })
  console.log(lycArr)
  return lycArr
}

// getLyc('/mp3/泉水.lyc')
// getLyc('/mp3/难说再见.lyc')
// getLyc('/mp3/光阴的故事.lyc')

// 绘制节奏灯
export const renderCanvas = (audioElement) => {

  let isInit = false;
  let analyser; // 分析波形节点
  let dataArray; // 存储分析好的对象

  const cvs = document.querySelector('#canvas')
  const ctx = cvs.getContext('2d')

  // 创建音频上下文
  const audioCtx = new AudioContext();
  // 加入音频源
  const source = audioCtx.createMediaElementSource(audioElement);
  // 创建解析节点
  analyser = audioCtx.createAnalyser();
  analyser.fftSize = 1024;
  // 第一次获取解析数据
  dataArray = new Uint8Array(analyser.frequencyBinCount);
  source.connect(analyser);
  analyser.connect(audioCtx.destination);
  isInit = true;
  console.log('dataArray', dataArray);
  const draw = () => {

    const { width, height } = cvs
    ctx.clearRect(0, 0, width, height)

    requestAnimationFrame(draw); // 微任务
    if (!isInit) {
      return
    }

    // 不断的获取 频率数据
    analyser.getByteFrequencyData(dataArray);
    // console.log('dataArray', dataArray);

    // 简化音柱: 需要 30 个音柱
    let num = 30; // 音柱的数量
    const offset = 2; // 音柱间隙
    let arr = chunk(dataArray, Math.ceil(dataArray.length / num)).map((arrItem) => {
      let sum = arrItem.reduce((res, item) => {
        res += item;
        return res;
      }, 0);
      let avg = Math.floor(sum / arrItem.length);
      return avg;
    })

    const gradient = ctx.createLinearGradient(0, height, 0, 0)

    // 添加颜色停止点
    gradient.addColorStop(0, 'rgba(67, 225, 16, 1)');       // 开始处的颜色
    gradient.addColorStop(0.5, 'rgba(67, 225, 16, .2)');      // 结束处的颜色

    ctx.fillStyle = gradient;

    let barWidth = (width / 2) / num; // 音柱的宽度
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      const barHeight = (item / 255) * height; // 音柱的高度
      const x1 = (width / 2) + (i * barWidth);
      const x2 = (width / 2) - ((i + 1) * barWidth);
      const y = height - barHeight;

      ctx.fillRect(x1 + offset, y, barWidth - offset, barHeight);
      ctx.fillRect(x2 + offset, y, barWidth - offset, barHeight);
    }
  }

  draw()
}
